import React, { useRef, useState } from "react";
import "./App.css";

function App() {
  const token = useRef('')
  const [data, setdata] = useState<{ id: number, userName: string }[]>([])

  const login = async () => {
    const userName = 'root'
    const passwd = 'admin_123'
    const response = await fetch('/api/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        userName,
        passwd
      })
    });
    response.json().then(res => {
      token.current = res.token
    });
  }

  const getData = async () => {
    if (!token.current) {
      alert('请先登录！')
    } else {
      const response = await fetch('/api/list', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'token': token.current
        },
      });
      response.json().then(res => {
        if (res.errCode === 0) {
          setdata(res.data)
        }
      });
    }
  }

  return (
    <div className="App">
      <button onClick={login}>登录</button>
      <button onClick={getData}>获取数据</button>
      {
        data.length > 0 && <ul>
          {
            data.map(res => <li key={res.id}>
              {res.userName}
            </li>)
          }
        </ul>
      }
    </div>
  );
}

export default App;
